﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using TruckScale.Helpers;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.Models
{
  public class WeighConfigModel
  {
    public int? AutoNo { get; set; }
    public string ConfigKey { get; set; }
    public string ConfigValue { get; set; }

    public static Dictionary<string,string> SelectConfig()
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = "select * from weighconfig;";
          IEnumerable<WeighConfigModel> output = cnn.Query<WeighConfigModel>(sql);

          return output.ToDictionary(o => o.ConfigKey, o => o.ConfigValue);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          Dictionary<string, string> _DefaultWeighConfig = new Dictionary<string, string>
          {
            {"Theme", "Office_Blue" },
            {"MainFontSize", "16" },
            {"AutoStart", "False" },
            {"StorePwd", "True" },
            {"AutoLogin", "False" },
            {"Protocol", "耀华" },
            {"StableDelay", "3" },
            {"WeighTemplateName", "销售磅单" },
            {"WeighMode", "2" },
            {"ShowSwitchWeighTemplate", "True" },
            {"ShowPrintButton", "False" },
            {"WeighSP", "COM1,9600,None,8,1" },
            {"PreviewPrint", "False" },
            {"WeighControl", "Auto" },
            {"MinWeight", "0" },
            {"RegCode", null },
            {"LastBackupTime", ""}
          };
          return _DefaultWeighConfig;
        }
      }
    }

    public static int UpdateConfig(string key, string value)
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          string sql = $"update weighconfig set config_value = '{value}' where config_key = '{key}';";
          return cnn.Execute(sql);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return -1;
        }
      }
    }

    public static int UpdateConfig(Dictionary<string, string> config)
    {
      using (IDbConnection cnn = DBHelper.DbConnection())
      {
        try
        {
          List<WeighConfigModel> configList = new List<WeighConfigModel>();
          config.ToList().ForEach(c =>
          {
            WeighConfigModel cm = new WeighConfigModel()
            {
              ConfigKey = c.Key,
              ConfigValue = c.Value
            };
            configList.Add(cm);
          });
          string sql = @"update weighconfig set config_value = @ConfigValue where config_key = @ConfigKey;";
          return cnn.Execute(sql, configList);
        }
        catch (Exception e)
        {
          SetLog(e.Message, LogType.OperationLogger, LogLevel.Error);
          return -1;
        }
      }
    }
  }
}
